package utils;

import android.annotation.SuppressLint;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.RemoteException;
import android.provider.OpenableColumns;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;

public class MyUtil {
    //判断字符串是否为空
    public static boolean isNull(Object s) {
        if (s == null) {
            return true;
        } else if (s.equals("null")) {
            return true;
        } else if (s.equals("")) {
            return true;
        } else if (s.toString().equals("{}")) {
            return true;
        } else if (s.toString().equals("[]")) {
            return true;
        }else if (s.toString().length() <= 0) {
            return true;
        } else {
            return false;
        }
    }
    // toast与log
    public static void showToast(Context ctx,String s) {
        Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
    }
    public static void showLog(String tag, Object obj) {
        if (!tag.equals("")) System.out.println("******"+tag+"******");
        if (!isNull(obj)) System.out.println(obj);
        // Log.v(tag.equals("")?"":tag, String.valueOf(obj));
    }
    // 日期格式化
    public static String formatDateTime(Date date) {
        SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss", Locale.getDefault());
        String myDate = format.format(date);
        return myDate;
    }
    // 日期格式化
    public static String formatDateTime2Num(Date date,int f) {
        String s = "yyyyMMddHHmmss";
        if (f==1) s = "yyyyMMdd";
        SimpleDateFormat format= new SimpleDateFormat(s, Locale.getDefault());
        String myDate = format.format(date);
        return myDate;
    }
    // long 转日期字符串
    public static String transferLongToDate(String dateFormat, Long millSec){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date= new Date(millSec);
        return sdf.format(date);
    }
    /**
     * 复制内容到剪切板
     *
     * @param copyStr
     * @return
     */
    public static boolean copyStr(Context ctx,String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            Toast.makeText(ctx, "文本复制成功", Toast.LENGTH_SHORT).show();
            return true;
        } catch (Exception e) {
            Toast.makeText(ctx, "文本复制失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    // 统计流量
    public static JSONObject getTrafficTotal(Context ctx, int uid) {
        long mobleRx = 0;
        long mobleTx = 0;
        long wifiRx = 0;
        long wifiTx = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkStatsManager networkStatsManager = null;
            networkStatsManager = (NetworkStatsManager) ctx.getSystemService(ctx.NETWORK_STATS_SERVICE);
            NetworkStats.Bucket bucket = null;
            long startTime = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 365 * 12;
            long endTime = System.currentTimeMillis() + 1000 * 60 * 60;
            if (uid==0) {
                try {
                    bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,null, startTime,endTime);
                    mobleRx = bucket.getRxBytes();
                    mobleTx = bucket.getTxBytes();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                try {
                    bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,null, startTime,endTime);
                    wifiRx = bucket.getRxBytes();
                    wifiTx = bucket.getTxBytes();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    NetworkStats moble = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_MOBILE, null, startTime, endTime, uid);
                    NetworkStats wifi = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, null, startTime, endTime, uid);
                    do {
                        NetworkStats.Bucket bkt = new NetworkStats.Bucket();
                        moble.getNextBucket(bkt);
                        mobleRx += bkt.getRxBytes();
                        mobleTx += bkt.getTxBytes();
                    } while (moble.hasNextBucket());
                    do {
                        NetworkStats.Bucket bkt = new NetworkStats.Bucket();
                        wifi.getNextBucket(bkt);
                        wifiRx += bkt.getRxBytes();
                        wifiTx += bkt.getTxBytes();
                    } while (wifi.hasNextBucket());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (uid==0) {
                mobleRx = TrafficStats.getTotalRxBytes();
                mobleTx = TrafficStats.getTotalTxBytes();
            }
        }
        JSONObject r = new JSONObject();
        try {
            r.put("mRx", mobleRx);
            r.put("mTx", mobleTx);
            r.put("wRx", wifiRx);
            r.put("wTx", wifiTx);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return r;
    }

    //收起软键盘
    public static void hideSoftInputFromWindow(Context ctx,EditText et) {
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
        }
    }

    // 获取uri文件名的方法
    @SuppressLint("Range")
    public static String getFileNameFromUri(Context context, Uri uri) {
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    // 获取本地图片资源
    public static Bitmap getImageFromAssetsFile(Context ctx, String fileName) {
        Bitmap image = null;
        AssetManager am = ctx.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }


    public static void getBoardInfo() {
        MyUtil.showLog("serialNum", android.os.Build.SERIAL);
        MyUtil.showLog("获取设备品牌", android.os.Build.BRAND);
        MyUtil.showLog("获取设备驱动名称", android.os.Build.DEVICE);
        MyUtil.showLog("获取设备显示的版本包", android.os.Build.DISPLAY);
        MyUtil.showLog("设备版本号", android.os.Build.ID);
        MyUtil.showLog("获取手机的型号", android.os.Build.MODEL);
        MyUtil.showLog("时间", android.os.Build.TIME);
    }

}
